const http = require("http");
const child_process = require('child_process');
const createHandler = require("git-webhook-handler");
const handler = createHandler({ path: "/hook", secret: "abc123" });

//cmd命令执行
function run_cmd(cmd, args, callback) {
  let spawn = child_process.spawn;
  let child = spawn(cmd, args);
  let resp = "";
  child.stdout.on("data", function (buffer) {
    resp += buffer.toString();
  });
  child.stdout.on("end", function () {
    callback(resp);
  });
}

http
  .createServer(function (req, res) {
    handler(req, res, function (err) {
      res.statusCode = 404;
      res.end("no such location");
    });
  })
  .listen(7777);

handler.on("error", function (err) {
  console.error("Error:", err.message);
});

handler.on("push", function (event) {
  console.log(
    "Received a push event for %s to %s",
    event.payload.repository.name,
    event.payload.ref
  );

  if(event.payload.ref==='refs/heads/master'){
    run_cmd('sh',['./deploy.sh'],function(text){
      console.log(text);
    })
  }
});

handler.on("issues", function (event) {
  console.log(
    "Received an issue event for %s action=%s: #%d %s",
    event.payload.repository.name,
    event.payload.action,
    event.payload.issue.number,
    event.payload.issue.title
  );
});
